import os
import json
import requests
import sys

#通知人手机
userMobile=os.getenv('JIANMU_USER_MOBILE')
#上线通知群
onlineGroupRebotToken=os.getenv('JIANMU_ONLINE_GROUP_REBOT_TOKEN')
# 服务名
jobName=os.getenv('JIANMU_JOB_NAME')

# 钉钉通知
def DingTalkNotify():
    args = sys.argv
    text = args[1]
    headers = {
    'Content-Type': 'application/json'
    }
    
    atMobiles = userMobile.split(',')
    atStr = ""
    for mobileIdStr in atMobiles:
        atStr += "@" + mobileIdStr + " "
	
    title = "{0}服务乐高平台发布后,检测到异常".format(jobName)
    text = text.replace("\\n", "  \n  ")
    text  = "#### **{0}**  \n  {1}  \n  {2}".format(title,text,atStr)
    print(text)
    data = {
        'msgtype': 'markdown',
        'markdown': {
            'title': title,
            'text': text
        },
        "at": {
            "atMobiles": atMobiles,
        }
    }
    url = "https://oapi.dingtalk.com/robot/send?access_token="
    url += onlineGroupRebotToken
    response = requests.post(url=url, headers=headers, data=json.dumps(data))
    content = response.json()
    if content.get("errcode") != 0:
        raise Exception(content)
    print("钉钉通知完成:"+json.dumps(content))

    return


if __name__ == "__main__":
  DingTalkNotify()      